(function ($, doc) {
    var userinfo = app.getState();
    var uid = userinfo.user_id;
    $.init({
        swipeBack:true,
        gestureConfig: {
            tap: true, //默认为true
            doubletap: true, //默认为false
            longtap: true, //默认为false
            swipe: true, //默认为true
            drag: true, //默认为true
            hold: true, //默认为false，不监听
            release: true //默认为false，不监听
        }
    });
    template.config('escape', false);
    

    
    $.plusReady(function () {
        var self        = plus.webview.currentWebview();
        var s_id        = self.s_id;
        var ui = {
            body: doc.querySelector('body'),
            footer: doc.querySelector('footer'),
            footerRight: doc.querySelector('.footer-left'),
            footerLeft: doc.querySelector('.footer-right'),
            btnMsgImage: doc.querySelector('#msg-type'),
            boxMsgText: doc.querySelector('#msg-text')
        };

        var record = [];
        //显示表情
        document.querySelector('#biaoqing').addEventListener('release', function(event) {
            if (this.classList.contains('icon-biaoqing')) {
                this.classList.add('jianpan');
                this.classList.remove('icon-biaoqing');
                document.querySelector('footer').style.bottom = '29%';
                document.querySelector('#biaoqingbao').style.display = 'block';
                ui.boxMsgText.style.display = 'block';
                document.body.focus();
                ui.boxMsgText.blur();
            } else if (this.classList.contains('jianpan')) {
                this.classList.add('icon-biaoqing');
                this.classList.remove('jianpan');
                ui.boxMsgText.style.display = 'block';
                document.querySelector('#biaoqingbao').style.display = 'none';
                document.querySelector('footer').style.bottom = '0px';
                ui.boxMsgText.focus();
                setTimeout(function() {
                    ui.boxMsgText.focus();
                }, 150);
            }
        }, false);

        mui('footer').on('tap','#msg-text',function() {
            document.querySelector('footer').style.bottom = '0px';
            document.querySelector('#biaoqingbao').style.display = 'none';
        });

        //选择表情
        mui('#selectFace').on('tap','img',function() {
            var faceImg     = this.getAttribute('src');
            var img         = document.createElement("img");
            img.src         = faceImg;
            //document.querySelector('#msg-text').appendChild(img);
            ui.boxMsgText.innerHTML += '<img src="' + faceImg + '" />';
            document.querySelector('.send').style.backgroundColor = '#1aad19';
            var a_id        = document.querySelector('.profile-detail-item').getAttribute('id'),
                t_name      = document.querySelector('.item-top').innerText,
                f_header    = document.querySelector('.profile-detail-item .item-logo img').getAttribute('src');
        });

        //显示发送按钮
        ui.boxMsgText.addEventListener('input', function(event) {
            if(ui.boxMsgText.innerHTML != ''){
                document.querySelector('.send').style.backgroundColor = '#1aad19';
            }else{
                document.querySelector('.send').style.backgroundColor = '#f5f5f5';
            }
            ui.btnMsgImage.setAttribute("for", ui.boxMsgText.value == '' ? '' : 'msg-text');
            // ui.h.innerText = ui.boxMsgText.innerHTML.replace(new RegExp('\n', 'gm'), '\n-') || '-';
            // ui.footer.style.height = (ui.h.offsetHeight + footerPadding) + 'px';
        });

        var msgTap = function (e) {
            var el  = this;
            var len = $("#pl .pl-long").length;
            var val = el.querySelector('.sp-l').getAttribute('cid');
            var fid = el.querySelector('.sp-l').getAttribute('fid');
            var con = el.querySelector('#content').innerText;
            if(fid == app.getState().user_id){
                var buttons = [ {
                    title: "复制"
                },{
                    title: "删除"
                }];
            }else{
                var buttons = [ {
                    title: "复制"
                }];
            }

            plus.nativeUI.actionSheet({
                title: "操作",
                cancel: "取消",
                buttons: buttons
            }, function(e) {
                if(e.index == 1) {
                    if(mui.os.android) {
                        var Context = plus.android.importClass("android.content.Context");
                        var main = plus.android.runtimeMainActivity();
                        var clip = main.getSystemService(Context.CLIPBOARD_SERVICE);
                        plus.android.invoke(clip,"setText",con);
                    } else {
                        var UIPasteboard = plus.ios.importClass("UIPasteboard");
                        var generalPasteboard = UIPasteboard.generalPasteboard();
                        generalPasteboard.setValueforPasteboardType(con, "public.utf8-plain-text");
                    }
                    $.toast("已复制");
                }else if(e.index == 2) {
                    var toUrl = apiurl + 'Friends/delComment';
                    mui.post(toUrl, {
                        c_id : val
                    }, function(res){
                        if(res.status == 1) {
                            if(len == 1){
                                document.querySelector('#pl').style.display = 'none';
                                document.querySelector('.pl-r').removeChild(el);
                            }else{
                                document.querySelector('.pl-r').removeChild(el);
                            }
                        }
                    })
                }
                return true;
            })
        }

        var bindMsgList = function (msg) {
            var divl = document.createElement("div");
            divl.className = 'pl-l';
            document.querySelector('#pl').appendChild(divl);
            var divr = document.createElement("div");
            divr.className = 'pl-r';
            var div1 = document.createElement("div");
            div1.className = 'item-logo';
            var img = document.createElement('img');
            var str = msg.f_header;
            if(str == ''){
                img.src = '../../static/images/1.png'
            }else if(str.indexOf("http") > -1){
                img.src = str;
            }else{
                img.src = serverurl + str;
            }
            div1.appendChild(img);
            var div2 = document.createElement('div');
            div2.className = 'item';
            var div3 = document.createElement('div');
            div3.className = 'item-url';
            var div4 = document.createElement('div');
            div4.className = 'item-url-image';
            var span1 = document.createElement('span');
            span1.className = 'sp-l';
            span1.innerText = msg.f_name;
            div4.appendChild(span1);
            var span2 = document.createElement('span');
            span2.className = 'sp-r';
            span2.innerText = '刚刚';
            div4.appendChild(span2);
            var p = document.createElement('p');
            p.innerHTML = msg.content;
            div4.appendChild(p);
            div3.appendChild(div4);
            div2.appendChild(div3);
            var div5 = document.createElement('div');
            div5.className = 'clear';
            divr.appendChild(div1);
            divr.appendChild(div2);
            divr.appendChild(div5);
            document.querySelector('#pl').appendChild(divr);
        };

        var send = function(msg) {
            bindMsgList(msg);
            toRobot(msg);
        };
        var toRobot = function(info){
            var toUrl = apiurl + 'friends/addcomment';
            var msgInfo = {
                f_id : userinfo.user_id,
                f_name : info.f_name,
                f_header: info.f_header,
                t_id : info.t_id,
                t_name : info.t_name,
                a_id : info.a_id,
                msg : info.content,
                type : info.type
            };
            mui.ajax(toUrl, {
                data: msgInfo,
                dataType: 'json', //服务器返回json格式数据
                type: 'post', //HTTP请求类型
                timeout: 0, //超时时间设置为3秒；
                headers: {
                    'Content-Type': 'application/json'
                },
                success: function(data) {
                    //ui.boxMsgText.blur();
                    console.log(data.status);
                },
                error: function(xhr, type, errorThrown) {
                    //异常处理；
                    console.log(type);
                }
            });
        };



        //显示键盘
        var focus = false;
        ui.boxMsgText.addEventListener('tap', function(event) {
            document.querySelector('#biaoqingbao').style.display = 'none';
            document.querySelector('footer').style.bottom = '0px';

            document.querySelector('#biaoqing').classList.add('icon-biaoqing');
            document.querySelector('#biaoqing').classList.remove('jianpan');

            // ui.content.style.paddingBottom = '50px';

            ui.boxMsgText.focus();
            setTimeout(function() {
                ui.boxMsgText.focus();
            }, 0);
            focus = true;
            setTimeout(function() {
                focus = false;
            }, 1000);
            event.detail.gesture.preventDefault();
        }, false);



        //发送文字
        document.querySelector('.send').addEventListener('click',function() {
            var a_id        = document.querySelector('.profile-detail-item').getAttribute('sid'),
                t_name      = document.querySelector('.item-top').innerText,
                t_id        = document.querySelector('.profile-detail-item').getAttribute('uid');
            ui.boxMsgText.focus();
            setTimeout(function() {
                ui.boxMsgText.focus();
                document.querySelector('#biaoqingbao').style.display = 'none';
                document.querySelector('footer').style.bottom = '0px';
            }, 150);
            send({
                sender: 'self',
                type: 'text',
                f_name: t_name,
                f_header: userinfo.avatar,
                t_name: t_name,
                a_id: a_id,
                t_id: t_id,
                content: ui.boxMsgText.innerHTML.replace(new RegExp('\n', 'gm'), '')
            });
            ui.boxMsgText.innerHTML = '';
            $.trigger(ui.boxMsgText, 'input', null);
        });

        $('#pl').on('longtap', '.pl-long', msgTap);
    })
}(mui, document));